package com.ancy.aynch;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Toast;

import com.ancy.common.ICommon;
import com.ancy.common.IError;
import com.ancy.common.IParams;
import com.ancy.common.PostData;
import com.ancy.manager.InternetManager;
import com.ancy.manager.ResponseManager;

public class RegisterTask extends AsyncTask<Void, Integer, Void> implements
		ICommon, IParams, IError {

	String username, password, email;
	View progress;
	Context context;
	String resString;

	public RegisterTask(String username, String password, String email,
			View progress, Context context) {
		// TODO Auto-generated constructor stub
		this.username = username;
		this.password = password;
		this.progress = progress;
		this.context = context;
	}

	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		progress.setVisibility(View.INVISIBLE);
		System.out.println("resString" + resString);
		if (!resString.equals("")) {
			JSONObject resObject;
			try {
				resObject = new JSONObject(resString);
				// Check whether the status code is 100 or not
				ResponseManager resMgr = new ResponseManager(resObject);
				if (resMgr.validateCode()) {
					// Close current screen
					((Activity) context).finish();
				}
				Toast.makeText(context, resObject.getString(RES_RESPONSE),
						Toast.LENGTH_SHORT).show();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			Toast.makeText(context, SERVER_CONNC_ERR, Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		progress.setVisibility(View.VISIBLE);
	}

	@Override
	protected Void doInBackground(Void... arg0) {
		// TODO Auto-generated method stub
		InternetManager mger = new InternetManager(URL_NEWUSER);

		ArrayList<PostData> toPost = new ArrayList<PostData>();

		PostData usernameObj = new PostData();
		usernameObj.setParam(REQ_UNAME);
		usernameObj.setValue(username);
		toPost.add(usernameObj);

		PostData passwordObj = new PostData();
		passwordObj.setParam(REQ_PASS);
		passwordObj.setValue(password);
		toPost.add(passwordObj);

		PostData emailObj = new PostData();
		emailObj.setParam(REQ_EMAIL);
		emailObj.setValue(email);
		toPost.add(emailObj);

		resString = mger.postData(toPost);
		return null;
	}
}
